package Userjava.Userdao;

import Userjava.Userpojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/*自动装载*/
@Component
public class UserDaoImpl implements User_Dao {

    @Autowired
    private JdbcTemplate jt;
    @Override
    public int save(User user) {
            String sql="INSERT INTO `ren`.`user` VALUES(null,?,?)";
        return jt.update(sql,user.getUname(),user.getUpwd());
    }
    @Override
    public int delete(User user) {
        String sql="delete from `user` where id=?";
        return jt.update(sql,user.getId());
    }

    @Override
    public int update(User user) {
        String sql="updata `user` set uname=?,upwd=? where id=?";
        return jt.update(sql,user.getUname(),user.getUpwd(),user.getId());
    }

    @Override
    public User queryUser(User user) {
        String sql="select `id`,`uname`,`upwd` from `ren`.`user` where uname=? and upwd=?";

       return jt.queryForObject(sql,new RowMapper<User>(){

           @Override
           public User mapRow(ResultSet resultSet, int i) throws SQLException {
               User user1=new User();
               user1.setId(resultSet.getInt("id"));
               user1.setUname(resultSet.getString("uname"));
               user1.setUpwd(resultSet.getString("upwd"));
               return user1;
           }
       },user.getUname(),user.getUpwd());

    }

    @Override
    public List<User> queryList() {
        String sql="select `id`,`uname`,`upwd` from `ren`.`user`";
        return jt.query(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user1=new User();
                user1.setId(resultSet.getInt("id"));
                user1.setUname(resultSet.getString("uname"));
                user1.setUpwd(resultSet.getString("upwd"));
                return user1;
            }
        });
    }
}
